<?php
/**
 *
 * @author HUYHQ
 *
 */
class Database
{
	/**
	 *@desc	value for connect to database
	 * @var $config = array(
	 * 	'dbtype' => '',
	 * 	'host' => '',
	 * 	'dbname' => '',
	 * 	'user' => '',
	 * 	'pass' => '',
	 *
	 * )
	 */
	protected static $config = array();

	/**
	 * @desc	Connection DB Value
	 */
	protected static $DB_Conn;

	/**
	 * @var <str> The mode to return results, defualt is MYSQL_BOTH, use setFetchMode() to change.
	 */
	private $fetchMode = MYSQL_BOTH;

	/**
	 * @desc		Creates the MySQLi object for usage.
	 *
	 * @param	<arr> $db Required connection params.
	 */
	public function  __construct() {
		$this->setConfigs();
	}

	public function setConfigs() {
		$_cfg = tsConfig::getInstance( CONF_FILE );
		// set facebook connect config
		$config = array();
		$config['host'] = $_cfg->get( 'DATABASE', 'host' );
		$config['user'] = $_cfg->get( 'DATABASE', 'user' );
		$config['pass'] = $_cfg->get( 'DATABASE', 'pass' );
		$config['db'] = $_cfg->get( 'DATABASE', 'db' );
		self::$config = $config;
	}

	/**
	 * @desc: Connect to host and select database name
	 */
	public static function connect(){
		self::$DB_Conn = mysql_connect(self::$config['host'], self::$config['user'], self::$config['pass'] );
		if (!self::$DB_Conn) {
			die('Could not connect: ' . mysql_error());
		}
		$db = mysql_select_db(self::$config['db'], self::$DB_Conn); // select db
		if(!$db){
			die('Could not select database: '.self::$config['db'].' '. mysql_error());
		}
	}

	/**
	 * @desc		Optionally set the return mode.
	 *
	 * @param	<int> $type The mode: 1 for MYSQLI_NUM, 2 for MYSQLI_ASSOC, default is MYSQLI_BOTH
	 */
	public  static function setFetchMode($type)
	{
		switch($type)
		{
			case 1:
				return MYSQL_NUM;

			case 2:
				return MYSQL_ASSOC;

			default:
				return MYSQL_BOTH;
		}

	}

	/**
	 * @desc	Get the results
	 *
	 * @param
	 * @return
	 */
	public static function fetchTable($query = NULL, $type = NULL)
	{
		/** Grab all the data */
		$data = array();
		if($query)
		{
			try{
				$result = mysql_query($query);
				if($result){
					while ($row = mysql_fetch_array($result, self::setFetchMode($type))){
						$data[] = $row;
					}
				}
			}catch (Exception $e){
				throw Exception( "Cannot execute query ".$query. ' '.mysql_error());
			}
		}
		return $data;
	}
	
	public static function executeQuery($query = NULL)
	{
			/** Grab all the data */			
			if($query)
			{
				try{
					return mysql_query($query);					
				}catch (Exception $e){
					throw Exception( "Cannot execute query ".$query. ' '.mysql_error());
					return FALSE;
				}
			}			
		}

	/**
	 * @desc	Automatically close the connection when finished with this object.
	 */
	public function __destruct()
	{
		if(self::$DB_Conn)
		@mysql_close(self::$DB_Conn);
	}

}